package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"strings"
)

var uploadpath = "upload"

func main() {

	//创建默认的引擎
	r := gin.Default()
	//创建请求 当访问地址为/uploadfile时执行后面的函数
	r.POST("/uploadfile", func(c *gin.Context) {
		var fileModel FileModel
		//获取表单数据 参数为name值
		f, err := c.FormFile("file")
		path := fmt.Sprintf("/%v/", uploadpath)
		//错误处理
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err,
			})
			return
		} else {
			fileModel.FileName = f.Filename
			fileModel.FileSize = f.Size / 1024
			fileModel.FileSuffix = strings.Split(f.Filename, ".")[1]
			fileModel.FileType = GetFileType(fileModel.FileSuffix)
			path = fmt.Sprintf("%v%v", path, fileModel.FileType)
			// 创建路径
			err := os.MkdirAll("."+path, os.ModePerm)
			if err != nil {
				fmt.Print(err)
			}
			path = fmt.Sprintf("%v/%v", path, f.Filename)
			dst := fmt.Sprintf(".%v", path)
			fileModel.FilePath = path
			//path+`\`+f.Filename
			//将文件保存至本项目根目录中
			_ = c.SaveUploadedFile(f, dst)
			//保存成功返回正确的Json数据
			c.JSON(http.StatusOK, gin.H{
				"data":    fileModel,
				"message": "OK",
			})
		}

	})
	//运行 默认为80端口
	_ = r.Run()
}

func CreatePath(path string) {
	os.MkdirAll(path, os.ModePerm)
}

// 名称 大小 后缀 类型 路径 MD5code  下载次数
type FileModel struct {
	FileName      string
	FileSize      int64
	FileSuffix    string
	FileType      string
	FilePath      string
	FileMD5Code   int64
	DownloadCount int64
}

var documents = "txt doc pdf ppt pps xlsx xls docx"
var music = "mp3 wav wma mpa ram ra aac aif m4a"
var video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg"
var image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg"
var compress = "zip rar 7z arj CAB ARJ LZH TAR GZ ACE UUE BZ2 JAR ISO MPQ"

func GetFileType(FileSuffix string) (FileType string) {

	suffix := strings.ToLower(FileSuffix)
	if strings.Contains(strings.ToLower(image), suffix) {
		FileType = "图片"
	} else if strings.Contains(strings.ToLower(documents), suffix) {
		FileType = "文档"
	} else if strings.Contains(strings.ToLower(music), suffix) {
		FileType = "音乐"
	} else if strings.Contains(strings.ToLower(video), suffix) {
		FileType = "视频"
	} else if strings.Contains(strings.ToLower(compress), suffix) {
		FileType = "压缩"
	} else {
		FileType = "其他"
	}
	return FileType
}
